/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mmt_server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import Message.Message;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

/**
 *
 * @author CUCAINHO
 */
public class MMT_SERVER {

    public static ArrayList<Socket> lstClientSocket;		
    public static ServerSocket server ;
        
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
       try
        {
                lstClientSocket = new ArrayList<Socket>();

                server = new ServerSocket(3211);

                do
                {	//System.out.print("a");
                    try{
                        Listen();
                    }catch(Exception e)
                    {
                        break;
                    }
                        //System.out.print("end a");
                }
                while (true);

        }
        catch(Exception e)
        {
                System.out.println("Error in Main!");
        }	
        
    }
    
    public static  void Listen() throws InterruptedException
    {
            try {			

                    System.out.println("Waiting for a Client connect...");

                    Socket ss = server.accept(); //synchronous			
                    lstClientSocket.add(ss);			
                    System.out.println("count accept " + lstClientSocket.size() +" name: "+  ss.toString());			
                    HandClient(ss);// nhan data tu client.


            }
            catch (IOException e) {

                    System.out.println("Loi khi listen client."+ e.toString());

            }

    }
	

	
	
	public static void HandClient(Socket ss)
	{
		try
		{						
                    ReciveClient rc = new ReciveClient(ss);			
			
		}
		catch(Exception e)
		{
                    System.out.println("Error in function HandClient!");
		}                
               
		
		
	}
        
        public static void HandMessage(Message ms){
            
            int type;
            type = ms.GetType();
            switch(type){
                case 1: // chat
                    HandChat(ms);
                    break;
                case 2:
                    break;
                case 3:
                    break;
                case 4:
                    break;
                case 5:
                    HandRemote(ms);
                    break;
                case 6:
                    break;
                case 7:
                    break;
                case 8:
                    break;
                case 9:
                    break;
                    
            }            
        }
        
        public static void  HandChat(Message ms){
            String str = ms.GetData().toString();
            System.out.println("Client: " + str);
        }
        
        public static void HandFile(Message ms){
            
        }
        
        public static void HandRemote(Message ms){
            int option = ms.GetOption();
            
            switch(option){
                
                case 1:
                    break;
                case 2:
                    XL_NhanHinhView(ms);
                    break;
                case 3:
                    break;    
                default:
                    break;
            }
            
        }
        
        public static void XL_NhanHinhView(Message ms){
            
            System.out.println("Nhan hinh.");
            
            JFrame frame = new JFrame();
             frame = new JFrame("QUẢN LÝ HỌC SINH");
             frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             ImageIcon img = new ImageIcon();
             img = (ImageIcon)ms.GetData();
             JPanel p = new JPanel();
             JLabel lb = new JLabel(img);
             lb.setSize(100,100);
             
             p.add(lb);
             frame.add(p);
             frame.setVisible(true);
             
                    
            
        }
          
        public static void HandViewDesktop(Message ms){
            
        }
            
        public static void HandShell(Message ms){
            
        }              
      
}

 class  ReciveClient extends MMT_SERVER implements Runnable { 
	
	private Socket theclient;  
	private ObjectInputStream in;
	public ReciveClient (Socket theclient) { 
		this.theclient = theclient; 		
		Thread t = new Thread(this); 
		t.start(); 
	} 
        
        public static void SendToClient(Socket theclient) throws IOException{           
             
            ObjectOutputStream out = new ObjectOutputStream(theclient.getOutputStream());
            System.out.println("Send Client! ");
            Object obj = new String("Server!!!");
            Message mssend = new Message(1,1,obj);
            out.writeObject(mssend);
        }
        
        public static void SendRequestViewDesktop(Socket theclient) throws IOException{ 
	 ObjectOutputStream out = new ObjectOutputStream(theclient.getOutputStream());
            System.out.println("Send Request view desktop ");
            Object obj = new String("Server!!!");
            Message mssend = new Message(5,1,obj);
            out.writeObject(mssend);
        }
	public void run() {             
                
            int k = 0;
		while(true){
                    
                  if(k % 10 == 0){
                        try {
                            SendToClient(theclient);
                        } catch (IOException ex) {
                            Logger.getLogger(ReciveClient.class.getName()).log(Level.SEVERE, null, ex);
                        }
                  }
                  if(k == 5){ // send yeu cau view desktop
                        try {
                            SendRequestViewDesktop(theclient);
                        } catch (IOException ex) {
                            Logger.getLogger(ReciveClient.class.getName()).log(Level.SEVERE, null, ex);
                        }
                  }
                  
		try 
		{  
                  
                  
                        in = new ObjectInputStream(theclient.getInputStream());
                        Message ms = new Message();
                try {
                       ms = (Message)in.readObject(); // doc message                  
                    } catch (Exception ex) {
                        System.out.println("Loi khi doc message." + ex.toString());
                        break;
                       // Logger.getLogger(ReciveClient.class.getName()).log(Level.SEVERE, null, ex);
                    }
                        
                        //while(ms != null) {	
                        if(ms != null) {
                            try
                            {                                    
                                HandMessage(ms);				
                            }catch(Exception ex){
                                System.out.println("OUT!");

                            }                                    
                              
			} 
                      	
		//System.out.println("Close socket in server!");		
		//this.lstClientSocket.remove(theclient);		
		//out.flush();	
		//out.close();
		//in.close(); 	
		//theclient.close(); 		
		} 
		catch (Exception e) { 
                        System.out.println("Client Disconnect!");
                        try {
                            theclient.close();
                        } catch (IOException ex) {
                            Logger.getLogger(ReciveClient.class.getName()).log(Level.SEVERE, null, ex);
                        }
                        break;
			//e.printStackTrace(); 
		}
                
                k++;
	} 
        }
	
}